package filecloud;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class FileCloud {
	private int redundancy = 2; //data will be saved in this many locations
	private List<CloudFile> dataLocations;
	
	public FileCloud(){
		//setDataLocations(File.listRoots());
		setDataLocations(getPresetDataLocations());
	}
	
	public static void main(String[] args) {
		FileCloud fc = new FileCloud();
		System.out.println(fc.getDataLocations());
		fc.saveData(null);
	}
	
	public void saveData(byte[] data){
		List<File> saveLocations = getSaveLocations();
		System.out.println(saveLocations);
	}
	
	private List<File> getSaveLocations() {
		ArrayList<File> saveLocations = new ArrayList<File>();
		List<CloudFile> dataLocations = getDataLocations();
		refreshCachedFreeSpace(dataLocations);
		Collections.sort(dataLocations, new FreeSpaceComparator());
		
		int numLocations = dataLocations.size();
		for(int i = 0; i < redundancy && i < numLocations; i++){
			saveLocations.add(dataLocations.get(i));
		}
		
		return saveLocations;		
	}
	
	private void refreshCachedFreeSpace(List<CloudFile> cloudFiles){
		for(CloudFile cf : cloudFiles){
			cf.refreshCachedFreeSpace();
		}
	}
	
	private File[] getPresetDataLocations(){
		File[] locations = new File[4];
		locations[0] = new File("C:\\temp");
		locations[1] = new File("P:\\");
		locations[2] = new File("X:\\public\\v\\temp");
		locations[3] = new File("T:\\temp\\v");
		
		return locations;
	}

	public synchronized void setDataLocations(List<CloudFile> dataLocations) {
		this.dataLocations = dataLocations;
	}
	
	public synchronized void setDataLocations(File[] dataLocations) {
		ArrayList<CloudFile> tempLocations = new ArrayList<CloudFile>();
		for(File file : dataLocations){
			tempLocations.add(new CloudFile(file.toURI()));
		}
		this.dataLocations = tempLocations;
	}

	public synchronized List<CloudFile> getDataLocations() {
		return dataLocations;
	}
}
